<?php

declare(strict_types=1);

namespace app\admin\controller;

use app\common\model\Export;
use app\model\FinanceDaily;
use Carbon\Carbon;
use think\Request;
use think\facade\Db;

class Finance extends Controller
{
    /**
     * @api {GET} /admin/finance/daily 对账单日报
     * @apiDescription 对账单日报
     * @apiName  financeDaily 对账单日报
     * @apiGroup Admin2_0
     * @apiParam {String} [dateymd[0]] 开始日期
     * @apiParam {String} [dateymd[1]] 结束日期
     * @apiParam {Number} [page=1] 页码
     * @apiParam {Number} [list_rows=10] 分页大小
     * @apiUse PageReturn
     * @apiVersion 1.0.0
     */
    public function daily(Request $request)
    {
        $dateYmd = $request->param('dateymd', [0 => '', 1 => '']);
        $where = [];
        if (!empty($dateYmd[0])) {
            $where[] = ['dateymd', '>=', $dateYmd[0]];
        }
        if (!empty($dateYmd[1])) {
            $where[] = ['dateymd', '<=', $dateYmd[1] . ' 23:59:59'];
        }

        if ($request->param('is_export')) {
            $list = FinanceDaily::where($where)->order('id desc')->select();

            if ($list->isEmpty()) {
                return fail('没有可导出的数据');
            }

            $list = $list->toArray();
            $exportTitle = [
                'dateymd' => '日期',
                'income' => '收入',
                'payout' => '支出',
                'profit' => '利润',
            ];
            $moneyCols = $exportTitle;
            unset($moneyCols['dateymd']);
            unset($moneyCols['profit']);
            foreach ($list as $k => $v) {
                foreach ($moneyCols as $k2 => $v2) {
                    $list[$k][$k2] = fen2yuan($v[$k2]);
                }
                $list[$k]['profit'] = $list[$k]['income'] - $list[$k]['payout'];
            }

            return Export::staticExport($list, $exportTitle, '财务对账单');
        } else {
            $list = FinanceDaily::where($where)->order('id desc')->paginate($this->getPaginate())->toArray();
            // 获取汇总数据
            $sum = FinanceDaily::where($where)->fieldRaw('sum(income) as income,sum(payout) as payout')->select();
            if ($sum->isEmpty()) {
                $sum = ['income' => 0, 'payout' => 0, 'profit' => 0];
            } else {
                $sum = ($sum->toArray())[0];
                $sum['profit'] = $sum['income'] - $sum['payout'];
            }
            $list['sum'] = $sum;
        }

        return success('', $list);
    }

    /**
     * 供应商列表
     */
    public function supplierList()
    {
        $mobileSupplier = Db::name('mobile_supplier')
            ->field('id, name')
            ->where('is_deleted', 0)
            ->order('id desc')
            ->select()
            ->toArray();
        $baseSupplier = Db::name('base_supplier')
            ->field('id, name, serv_type')
            ->whereNull('deleted_at')
            ->order('id desc')
            ->select()
            ->toArray();

        $res = [];
        $res[PRODUCT_MOBILE_SERV] = $mobileSupplier;
        foreach ($baseSupplier as $v) {
            $res[$v['serv_type']][] = [
                'id' => $v['id'],
                'name' => $v['name'],
            ];
        }

        return success('操作成功', $res);
    }

    /**
     * @api {GET} /admin/finance/dailyDetailList 对账单日报明细
     * @apiDescription 对账单日报明细
     * @apiName  financeDailyDetailList 对账单日报明细
     * @apiGroup Admin2_0
     * @apiParam {Number} serv_type 业务类型
     * @apiParam {String} [dateymd_from] 开始日期，不传默认当天
     * @apiParam {String} [dateymd_end] 结束日期，不传等于结束日期
     * @apiParam {Number} [supplier_id] 供应商id
     * @apiParam {Number} [agent_id] 代理商id
     * @apiParam {Number} [page=1] 页码
     * @apiParam {Number} [list_rows=10] 分页大小
     * @apiUse PageReturn
     * @apiVersion 1.0.0
     */
    public function dailyDetailList()
    {
        $where = [];
        $where[] = ['stat_time', '<>', 1];
        $params = input('post.');
        if (empty($params['dateymd_from'])) {
            return fail('开始日期不能为空');
        }
        if (empty($params['dateymd_end'])) {
            return fail('结束日期不能为空');
        }
        //        $days = ceil((strtotime($params['dateymd_end'] . ' 23:59:59') - strtotime($params['dateymd_from'])) / 68400);
//        if ($days > 30) {
//            return fail('时间区间不能超过 30 天');
//        }


        $dateymd_end = $params['dateymd_end'];
        $dateymd_from = $params['dateymd_from'];

        do {
            $valid = Carbon::hasFormat($dateymd_end, 'Y-m');

            if ($valid) {
                $dateymd_end = Carbon::parse($dateymd_end)->endOfMonth()->format('Y-m-d H:i:s');
                break;
            }
            $dateymd_end = Carbon::parse($dateymd_end)->endOfDay()->format('Y-m-d H:i:s');
        } while (false);

        $dateymd_from =  Carbon::parse($dateymd_from)->startOfDay()->format('Y-m-d H:i:s');


        $where[] = ['created_at', 'between time', [$dateymd_from, $dateymd_end]];

        $orderId = trim($params['order_id'] ?? '');
        if ($orderId) {
            $where[] = ['order_id', 'like', $orderId.'%'];
        }
        if (!empty($params['order_type'])) {
            $where[] = ['order_type', '=', $params['order_type']];
        }
        if (!empty($params['supplier_id'])) {
            $where[] = ['supplier_id', '=', $params['supplier_id']];
        }
        if (!empty($params['agent_id'])) {
            $where[] = ['agent_id', '=', $params['agent_id']];
        }
        $agentName = trim($params['agent_name'] ?? '');
        if ($agentName) {
            $agentIds = Db::name('agent')
                ->where('is_deleted', 0)
                ->where('username|company_name', '=', $agentName)
                ->column('id');
            if (empty($agentIds)) {
                $where[] = ['id', '=', 0];
            } else {
                $where[] = ['agent_id', 'in', $agentIds];
            }
        }

        $mobileSupplier = Db::name('mobile_supplier')
            // ->where('is_deleted', 0)
            ->column('name', 'id');
        $baseSupplier = Db::name('base_supplier')
            // ->whereNull('deleted_at')
            ->column('name', 'id');

        $db = Db::name('finance_detail')
            ->where($where)
            ->order('id desc');

        if (!empty($params['is_export'])) {
            $list = $db->select()->toArray();
            $agentIds = array_unique(array_column($list, 'agent_id'));
            $agent = Db::name('agent')
                ->whereIn('id', $agentIds)
                ->column('username, company_name', 'id');
            $res = [];
            $title = ['订单号', '订单类型', '时间', '结算方式', '销售价', '代理商结算价', '供应商结算价', '代理商利润', '平台利润', '代理商用户名', '代理商公司名称', '供应商', '备注'];
            foreach ($list as $v) {
                if ($v['order_type'] == PRODUCT_MOBILE_SERV) {
                    $supplierName = $mobileSupplier[$v['supplier_id']] ?? '';
                } else {
                    $supplierName = $baseSupplier[$v['supplier_id']] ?? '';
                }
                $res[] = [
                    $v['order_id']."\t",
                    PRODUCT_SERV_TYPE[$v['order_type']]['orderName']??'',
                    $v['created_at'],
                    $v['settle_type'] == 1 ? '返佣' : '预付',
                    fen2yuan($v['sale_price']).'',
                    fen2yuan($v['settle_price']).'',
                    fen2yuan($v['supplier_price']).'',
                    fen2yuan($v['profit']).'',
                    fen2yuan($v['platform_profit']).'',
                    $agent[$v['agent_id']]['username'] ?? '',
                    $agent[$v['agent_id']]['company_name'] ?? '',
                    $supplierName,
                    $v['remark'],
                ];
            }
            unset($list);
            $export = new Export;
            $name = '财务对账单';
            return $export->downloadExcel($title, $res, $name);
        }

        $list = $db->paginate([
            'page' => $params['page'] ?? 1,
            'list_rows' => $params['list_rows'] ?? 10,
        ])->toArray();
        if ($list['data']) {
            $agentIds = array_unique(array_column($list['data'], 'agent_id'));
            $agent = Db::name('agent')
                ->whereIn('id', $agentIds)
                ->column('username, company_name', 'id');
            foreach ($list['data'] as $k => $v) {
                $list['data'][$k]['agent_name'] = $agent[$v['agent_id']]['username'] ?? '';
                $list['data'][$k]['company_name'] = $agent[$v['agent_id']]['company_name'] ?? '';
                if ($v['order_type'] === PRODUCT_MOBILE_SERV) {
                    $list['data'][$k]['supplier_name'] = $mobileSupplier[$v['supplier_id']] ?? '';
                } else {
                    $list['data'][$k]['supplier_name'] = $baseSupplier[$v['supplier_id']] ?? '';
                }
            }

            $list['sum'] = $db->field('sum(profit) profit, sum(platform_profit) platform_profit, sum(supplier_price) supplier_price')->find();
        } else {
            $list['sum'] = [
                'profit' => 0,
                'platform_profit' => 0,
                'supplier_profit' => 0,
            ];
        }

        return success('', $list);
    }
}
